#include <stdio.h>
#include <stdlib.h>

#include <string.h>

#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h> 
#include <arpa/inet.h> 

int main(int argc, char **argv)
{
	struct sockaddr_in my_addr, remote_addr;
	socklen_t length = sizeof(struct sockaddr_in);

	int my_sock = 0;

	char buffer[1024];

	bzero(&my_addr, sizeof(my_addr));
	bzero(&remote_addr, sizeof(remote_addr));

	my_addr.sin_family = AF_INET;
	my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	my_addr.sin_port = htons(60001);

	my_sock = socket(AF_INET, SOCK_DGRAM, 0);
	if(0 > my_sock)
	{
		printf("socket() failed\n");
		return EXIT_FAILURE;
	}

	if(-1 == bind(my_sock, (struct sockaddr *)&my_addr, sizeof(my_addr)))
	{
		printf("bind() failed\n");
		return EXIT_FAILURE;
	}

	while(1)
	{
		bzero(buffer, sizeof(buffer));
		if(0 >= recvfrom(my_sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&remote_addr, &length))
		{
			printf("recvfrom() failed\n");
			return EXIT_FAILURE;
		}
		else
		{
			if(0 == strcmp(buffer, "hello"))
			{
				snprintf(buffer, sizeof(buffer), "%s:%d", inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port));
				if(0 >= sendto(my_sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&remote_addr, sizeof(remote_addr)))
				{
					printf("send failed\n");
				}
				else
				{
					printf("recv client success\n");
					continue;
				}
			}
			else
			{
				printf("Message -> %s <=== %s:%d\n", buffer, inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port));
			}
		}
	}
	return EXIT_SUCCESS;
}
